import axios, { AxiosError, AxiosInstance, AxiosRequestConfig } from 'axios'
import useUserStore from '@/store/user'
import { ElMessage } from 'element-plus'
import { Response, HttpStatus, codeStatus, ApiResponse } from './request.type'

const request: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 50000
})

request.interceptors.request.use(
  (config) => {
    const { token } = useUserStore()
    if (token && config.headers) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

request.interceptors.response.use(
  (response: Response<any>) => {

    if (response.data.code === HttpStatus.Unauthorized) {
      const errText = '权限不足或者未登录'
      ElMessage.error(errText)

      const store = useUserStore()
      store.logout()
      return Promise.reject(new Error(errText))
    }

    if (response.data.code !== codeStatus.Success) {
      const errText = response.data.message || 'Error'
      ElMessage.error(errText)
      return Promise.reject(new Error(errText))
    }

    return response
  },
  (error: AxiosError<ApiResponse>) => {
    const response = error.response

    if (!response) {
      return Promise.reject(error)
    }

    if (response.status === HttpStatus.Unauthorized) {
      const errText = '权限不足或者未登录'
      ElMessage.error(errText)
      return Promise.reject(new Error(errText))
    }

    if (response.data.code !== codeStatus.Success) {
      const errText = response.data.message || 'Error'
      ElMessage.error(errText)
      return Promise.reject(new Error(errText))
    }

    return Promise.reject(error)
  }
)

const requestCommon = async <T extends any = any>
  (config: AxiosRequestConfig): Promise<ApiResponse<T>> => {
  const { data } = await request(config)
  return data
}

export default requestCommon
